package edu.zcmu.seckill.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
/**
 * @Author: tang
 * @Date: 2022/02/17/22:41
 * @Description:
 */
@ConfigurationProperties(prefix = "config.jwt")
@Component
public class JwtUtil {
    private String secret;
    private long expire;
    private String header;
    private static final String TOKEN = "xpp@ll";

    /**
     * 生成token
     * @return
     */
    public String createToken (Map<String, String> map){
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);//过期时间
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);

        });
        //指定令牌过期时间
        String token = builder.withExpiresAt(expireDate)
                //sign，传入加密盐
                .sign(Algorithm.HMAC256(TOKEN));
        return token;

    }
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
        return verify;
    }
    // --------------------- getter & setter ---------------------

    public String getSecret() {
        return secret;
    }
    public void setSecret(String secret) {
        this.secret = secret;
    }
    public long getExpire() {
        return expire;
    }
    public void setExpire(long expire) {
        this.expire = expire;
    }
    public String getHeader() {
        return header;
    }
    public void setHeader(String header) {
        this.header = header;
    }
}
